
axios.get('/student/list')
  .then(res => {
    //  console.log(res.data.data);
    const sobj = res.data.data;
    renderNativePlace(res.data.data);
  })

axios.get('/geo/province')
  .then(res => {
    // console.log(res.data);

  });
// 根据数据 渲染生成 籍贯信息
const newList = []; const lxobj = [];
function renderNativePlace(list) {
  // 对旧数组做遍历
  list.forEach((item) => {
    const index = newList.findIndex(
      (element) => item.province === element.name
    );
    if (index === -1) {
      newList.push({ name: item.province, value: 1 });
    } else {
      newList[index].value++;
    }
  });
  // console.log(newList);
  newList.forEach(v => {
    const arr = [];
    if (arr.indexOf(v) == -1) {
      arr.push(v);
    }
    lxobj.push(arr);
  })
  console.log(lxobj);
  map()
  //饼状图
  const chartDom = document.querySelector('.pie');
  const myChart = echarts.init(chartDom);
  let option;
  option = {
    title: {
      text: '学员籍贯'
    },
    legend: {
      top: 'bottom'
    },
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b} : {c} ({d}%)'
    },
    toolbox: {
      show: true,
      feature: {
        mark: { show: true },
        dataView: { show: true, readOnly: false },
        restore: { show: true },
        saveAsImage: { show: true }
      }
    },
    series: [
      {
        name: '各地分布的人数',
        type: 'pie',
        radius: [50, 110],
        center: ['50%', '50%'],
        roseType: 'area',
        itemStyle: {
          borderRadius: 8
        },
        data: newList,
      }
    ]
  };
  option && myChart.setOption(option);
}

//获取班上的人数
axios.get('/student/list')
  .then(res => {
    document.querySelector(".total").innerText = res.data.data.length;
    //获取所有人的真实薪资存放到一个数组里面
    const obj = res.data.data;
    const salaryArr = [];
    const ageArr = [];
    const man = [], woman = [];

    for (const key in obj) {
      salaryArr.push(obj[key].salary);
      const avg = (salaryArr.reduce((h, v) => h += v, 0)) / salaryArr.length;
      document.querySelector(`.avgSalary`).innerText = _comma(parseInt(avg))
    };

    for (const key in obj) {
      salaryArr.push(obj[key].salary);
      const avg = (salaryArr.reduce((h, v) => h += v, 0)) / salaryArr.length;
      document.querySelector(".avgSalary").innerText = _comma(parseInt(avg))
    };
    for (const key in obj) {
      ageArr.push(obj[key].age);
      const avg = (ageArr.reduce((h, v) => h += v, 0)) / ageArr.length;
      document.querySelector(".avgAge").innerText = parseInt(avg)
    };
    //获取男女比例
    for (const key in obj) {
      if (obj[key].sex === "男") {
        man.push(obj[key].name);
      } else if (obj[key].sex === "女") {
        woman.push(obj[key].name);
      }
    }
    document.querySelector(".proportion").innerText = parseFloat((man.length) / (woman.length)).toFixed(2);
  })
//获取薪资分隔符
function _comma(number) {
  let str = number.toString();
  return str.replace(/(\d)(?=(?:\d{3})+$)/g, '$1,');
}
//折线图
function ZX() {
  //拿名字
  axios.get('/student/list')
    .then(res => {
      // const obj = res.data.data;
      // const arr = [];
      // for (const key in obj) {
      //   //  console.log(obj[key].name);
      //   arr.push(obj[key].name)
      //   let chartDom = document.querySelector('.line');

      //   //拿薪资
      //   const Ssarlay = [];
      //   const Zsarlay = [];
      //   for (const key in obj) {
      //     Ssarlay.push(obj[key].salary);
      //     Zsarlay.push(obj[key].truesalary);
      //   };
      const list = res.data.data;
      console.log(list)
      const ts = list.map(v => v.truesalary);
      const s = list.map(v => v.salary)
      const names = list.map(v => v.name)
      let myChart = echarts.init(document.querySelector(".line"));
      const option = {
        title: {
          text: '薪资对比'
        },
        dataZoom: [
          {
            show: true,
            realtime: true,
            start: 0,
            end: 10,
          },
          {
            type: 'inside',
            realtime: true,
            start: 0,
            end: 10,
          }
        ],
        tooltip: {
          trigger: 'axis'
        },
        legend: {},
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: names,
        },
        yAxis: {},
        series: [
          {
            name: '真实薪资',
            type: 'line',
            smooth: true,
            symbol: 'circle',
            data: ts,

          },
          {
            name: '期望薪资',
            type: 'line',
            smooth: true,
            symbol: 'circle',
            data: s,
          }
        ]
      };
      option && myChart.setOption(option);

    });

}

ZX();

//柱状图
// 根据 成绩次数来加载成绩数据
function getScoreByBatch(index) {
  axios({
    url: '/score/batch',
    params: {
      batch: index,
    },
  }).then((result) => {
    if (result.data.code !== 0) {
      // 有问题
      toastr.warning(result.data.message);
      return;
    }

    //组名
    const group = result.data.data.group;
    //平均分
    const avgScore = result.data.data.avgScore;
    //小于60分人数
    const lt60 = result.data.data.lt60;
    //60~80分之间的人数
    const gt60 = result.data.data.gt60;
    //80以上的人数
    const gt80 = result.data.data.gt80;

    // 基于准备好的dom，初始化echarts实例
    const myChart = echarts.init(document.querySelector('.barChart'));

    // 指定图表的配置项和数据
    const option = {
      // 属性
      grid: {
        // 让图表网上拉伸到哪里
        top: 25,
        // 让图表网下拉伸到哪里
        bottom: 20,
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'cross',
          crossStyle: {
            color: '#999',
          },
        },
      },
      legend: {
        // 组名的数据
        data: ['平均分', '小于60分人数', '60~80分之间', '80以上的人数'],
      },
      xAxis: [
        {
          type: 'category',
          // x坐标的数据
          data: group,
          axisPointer: {
            type: 'shadow',
          },
        },
      ],
      yAxis: [
        {
          type: 'value',
          min: 0,
          max: 100,
          // 刻度
          interval: 10,
          axisLabel: {
            formatter: '{value}分',
          },
        },
        {
          type: 'value',
          min: 0,
          max: 10,
          interval: 1,
          axisLabel: {
            formatter: '{value}人',
          },
        },
      ],
      series: [
        {
          name: '平均分',
          type: 'bar',
          barWidth: 17,
          data: avgScore,
        },
        {
          name: '小于60分人数',
          type: 'bar',
          barWidth: 17,
          // 用 右边y轴刻度
          yAxisIndex: 1,
          data: lt60,
        },
        {
          name: '60~80分之间',
          type: 'bar',
          barWidth: 17,
          // 用 右边y轴刻度
          yAxisIndex: 1,
          data: gt60,
        },
        {
          name: '80以上的人数',
          type: 'bar',
          barWidth: 17,
          // 用 右边y轴刻度
          yAxisIndex: 1,
          data: gt80,
        },
      ],
    }; // 使用刚指定的配置项和数据显示图表。
    myChart.setOption(option);
  });
}

toggleBatchBtn.addEventListener('click', function (e) {
  // 如果你是隐藏 就显示
  // 如果你是显示 就隐藏
  if (batch.style.display === 'none' || batch.style.display === '') {
    batch.style.display = 'flex';
  } else {
    batch.style.display = 'none';
  }
});

// 根据 成绩次数来加载成绩数据
getScoreByBatch(1);

// 给成绩菜单绑定点击事件
batch.addEventListener('click', function (e) {
  if (e.target.tagName === 'A') {
    const { index } = e.target.dataset;
    getScoreByBatch(index);
  }
});


//中国地图
function map() {
  let uploadedDataURL = "https://geo.datav.aliyun.com/areas_v3/bound/100000_full.json";
  let chinaGeoCoordMap = {
    广东省: [113.12244, 23.009505],
    北京市: [116.4551, 40.2539],
    天津市: [117.4219, 39.4189],
    河北省: [114.4995, 38.1006],
    山西省: [112.3352, 37.9413],
    内蒙古自治区: [110.3467, 41.4899],
    辽宁省: [123.1238, 42.1216],
    吉林省: [125.8154, 44.2584],
    黑龙江省: [127.9688, 45.368],
    上海市: [121.4648, 31.2891],
    江苏省: [118.8062, 31.9208],
    浙江省: [119.5313, 29.8773],
    安徽省: [117.29, 32.0581],
    福建省: [119.4543, 25.9222],
    江西省: [116.0046, 28.6633],
    山东省: [117.1582, 36.8701],
    河南省: [113.4668, 34.6234],
    湖北省: [114.3896, 30.6628],
    湖南省: [113.0823, 28.2568],
    广西壮族自治区: [108.479, 23.1152],
    海南省: [110.3893, 19.8516],
    重庆市: [108.384366, 30.439702],
    四川省: [103.9526, 30.7617],
    贵州省: [106.6992, 26.7682],
    云南省: [102.9199, 25.4663],
    西藏自治区: [91.11, 29.97],
    陕西省: [109.1162, 34.2004],
    甘肃省: [103.5901, 36.3043],
    青海省: [101.4038, 36.8207],
    宁夏回族自治区: [106.3586, 38.1775],
    新疆维吾尔自治区: [87.9236, 43.5883],
  };

  let chinaDatas = lxobj;
  console.log(chinaDatas)
  function randomValue() {
    return Math.ceil(Math.random() * 10000 + 1);
  }

  let convertData = function (data) {
    let res = [];
    for (let i = 0; i < data.length; i++) {
      let dataItem = data[i];
      let fromCoord = chinaGeoCoordMap[dataItem[0].name];
      // console.log(dataItem[0].name)
      let toCoord = [113.12244, 23.009505];
      if (fromCoord && toCoord) {
        res.push([
          {
            coord: fromCoord,
            // value: dataItem[0].value
            value: randomValue(),
          },
          {
            coord: toCoord,
          },
        ]);
      }
    }
    return res;
  };
  let series = [];

  [["广东省", chinaDatas]].forEach(function (item, i) {
    // console.log(item)
    series.push(
      {
        type: "lines",
        zlevel: 2,
        effect: {
          show: true,
          period: 4, //箭头指向速度，值越小速度越快
          trailLength: 0.02, //特效尾迹长度[0,1]值越大，尾迹越长重
          symbol: "arrow", //箭头图标
          symbolSize: 5, //图标大小
        },
        lineStyle: {
          normal: {
            width: 1, //尾迹线条宽度
            opacity: 1, //尾迹线条透明度
            curveness: 0.3, //尾迹线条曲直度
          },
        },
        data: convertData(item[1]),
      },
      {
        type: "effectScatter",
        coordinateSystem: "geo",
        zlevel: 2,
        rippleEffect: {
          //涟漪特效
          period: 4, //动画时间，值越小速度越快
          brushType: "stroke", //波纹绘制方式 stroke, fill
          scale: 4, //波纹圆环最大限制，值越大波纹越大
        },
        label: {
          normal: {
            show: true,
            // position: "right", //显示位置
            // offset: [5, 0], //偏移设置
            formatter: function (params) {
              //圆环显示文字
              return params.data.name;
            },
            fontSize: 13,
          },
          emphasis: {
            show: true,
          },
        },
        symbol: "circle",
        symbolSize: function (val) {
          return 3 + val[2] / 600; //圆环大小
        },
        symbolSize: 8,
        itemStyle: {
          normal: {
            show: true,
            color: "#f00",
          },
        },
        data: item[1].map(function (dataItem) {
          return {
            name: dataItem[0].name,
            value: chinaGeoCoordMap[dataItem[0].name],
          };
        }),
      },
      //被攻击点
      {
        type: "scatter",
        coordinateSystem: "geo",
        zlevel: 2,
        rippleEffect: {
          period: 4,
          brushType: "stroke",
          scale: 4,
        },
        label: {
          normal: {
            show: true,
            color: "#0f0",
            formatter: "{b}",
            textStyle: {
              color: "#0f0",
            },
          },
          emphasis: {
            show: true,
            color: "#f60",
          },
        },
        symbol: "pin",
        symbolSize: 50,
        data: [
          {
            name: item[0],
            value: chinaGeoCoordMap[item[0]].concat([randomValue()]),
          },
        ],
      }
    );
  });
  const json = mapDate;
  echarts.registerMap("world", json);
  // console.log(json);

  option = {
    title: {
      text: '学员生源地'
    },
    tooltip: {
      trigger: "item",
      backgroundColor: "rgba(166, 200, 76, 0.82)",
      borderColor: "#FFFFCC",
      showDelay: 0,
      hideDelay: 0,
      enterable: true,
      transitionDuration: 0,
      extraCssText: "z-index:100",
      formatter: function (params, callback, lxobj) {
        //根据业务自己拓展要显示的内容
        let res = "";
        let name = params.name;
        res =
          "<span style='color:#fff;'>" + name;
        return res;
      },
    },
    backgroundColor: "white",
    visualMap: {
      //图例值控制
      min: 0,
      max: 10000,
      calculable: true,
      show: false,
      color: ["#f44336", "#fc9700", "#ffde00", "#ffde00", "#10eaff"],
      textStyle: {
        color: "#fff",
      },
    },
    geo: {
      map: "world",
      zoom: 1.7,
      center: [104.2978515625, 35.8544921875],
      label: {
        emphasis: {
          show: false,
        },
      },
      // roam: true, //是否允许缩放
      itemStyle: {
        normal: {
          color: "rgba(84, 112,198, .5)", //地图背景色
          borderColor: "#516a89", //省市边界线00fcff 516a89
          borderWidth: 1,
        },
        emphasis: {
          color: "rgba(37, 43, 61, .5)", //悬浮背景
        },
      },
      regions: [
        {
          name: "China",
          itemStyle: {
            normal: {
              borderColor: "white",
              borderWidth: 1,
              // areaColor: '#00f',
              areaColor: {
                type: "linear",
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [
                  {
                    offset: 0,
                    color: "#ff6600", // 0% 处的颜色
                  },
                  {
                    offset: 1,
                    color: "#0066ff", // 100% 处的颜色
                  },
                ],
                globalCoord: false, // 缺省为 false
              },
              shadowColor: "rgba(128, 217, 248, 1)",
              // shadowColor: 'rgba(255, 255, 255, 1)',
              shadowOffsetX: 0,
              shadowOffsetY: 0,
              shadowBlur: 10,
            },
            emphasis: {
              areaColor: "#389BB7",
              borderWidth: 0,
            },
          },
        },
      ],
    },
    series: series,
  };
  const chartDom = document.querySelector('.map');
  const myChart = echarts.init(chartDom);
  myChart.setOption(option);
}
